package main

import (
	"fmt"

	"github.com/boltdb/bolt"
)

// 区块链迭代器

// BlockchainIterator 区块链迭代器
type BlockchainIterator struct {
	currentHash []byte
	db          *bolt.DB
}

// Next 获取下一个区块(上一个区块)
func (i *BlockchainIterator) Next() *Block {
	var block *Block
	err := i.db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(blocksBucket))
		encodedBlock := b.Get(i.currentHash)
		block = DeserializeBlock(encodedBlock)
		return nil
	})
	if err != nil {
		fmt.Println("failed to get next block")
	}
	i.currentHash = block.PrevBlockHash
	return block
}
